package cz.hanis.android.geography.activities;

import java.util.List;

import cz.hanis.android.geography.R;
import cz.hanis.android.geography.TestActivity;
import cz.hanis.android.geography.TimeTestActivity;
import cz.hanis.android.geography.models.Country;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class CountryCapitalTestTimeActivity extends TimeTestActivity {

	private TextView tvCountry;	
	private int correct;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTestLayout(R.layout.country_capital_test);
		setQuestion(getString(R.string.tv_country_capital_question));
		tvCountry = (TextView) findViewById(R.id.tv_country_capital_country);
		setQuestionView(tvCountry);
		addAnswerView((Button) findViewById(R.id.bt_country_capital_capital1));
		addAnswerView((Button) findViewById(R.id.bt_country_capital_capital2));
		addAnswerView((Button) findViewById(R.id.bt_country_capital_capital3));
		setListeners();
		newRound();
	}
	

	private void setListeners() {
		int i=0;
		for(View view : getAnswerViews()) {
			final int index = i++;
			view.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					answer(index);
				}
			});
		}
	}		
	
	@Override
	protected int onAnswer(int answer) {		
		int result = ANSWERE_NONE;
		colorButton(correct, Color.GREEN);
		
		if (answer == correct) {
			result = ANSWERE_CORRECT;
		} else if (answer == ANSWERE_TIMED_OUT) {
			result = ANSWERE_TIMED_OUT;
		} else {
			colorButton(answer, Color.parseColor(getString(R.color.red2)));
			result = ANSWERE_INCORRECT;
		}
		return result;
	}
	
	private void colorButton(int location, int color) {
		Button button = (Button) getAnswerViews().get(location);
		button.setTextColor(color);
	}

	@Override
	protected void onNewRound() {
		for (int i = 0; i < getNumberOfAnswers() ;i++) {
			colorButton(i, Color.WHITE);
		}
		List<Country> randomCountries = getTools().getRandomCountries(getNumberOfAnswers(),
				getTest().getContinent());
		correct = getTools().getRandom(getNumberOfAnswers());
		String name = randomCountries.get(correct).getName();
		tvCountry.setText(name);
		
		for(int i = 0; i < getNumberOfAnswers(); i++) {
			Button button = (Button) getAnswerViews().get(i);
			button.setText(randomCountries.get(i).getCapital());
		}
	}
	
	
	
	
}
